import React, { useState, useEffect } from 'react';

interface StyleManagerProps {
  content: string;
  onStyleChange: (styleConfig: { theme: string, headingStyles: Record<number, React.CSSProperties> }) => void;
}

const StyleManager: React.FC<StyleManagerProps> = ({ content, onStyleChange }) => {
  // 定义主题色系方案
  const themes = {
    default: {
      primary: '#333',
      secondary: '#666',
      accent: '#667eea',
      background: '#fff',
    },
    blue: {
      primary: '#165DFF',
      secondary: '#4080FF',
      accent: '#0E42D2',
      background: '#F0F5FF',
    },
    green: {
      primary: '#00B42A',
      secondary: '#52C41A',
      accent: '#00873D',
      background: '#F6FFED',
    },
    orange: {
      primary: '#FF7D00',
      secondary: '#FF9500',
      accent: '#FA8C16',
      background: '#FFF7E6',
    },
    purple: {
      primary: '#722ED1',
      secondary: '#9254DE',
      accent: '#5D1FC5',
      background: '#F9F0FF',
    },
    red: {
      primary: '#F5222D',
      secondary: '#FF4D4F',
      accent: '#CF1322',
      background: '#FFF1F0',
    },
  };

  // 当前选择的主题
  const [selectedTheme, setSelectedTheme] = useState('default');
  // 标题层级信息
  const [headings, setHeadings] = useState<{ level: number; text: string; count: number }[]>([]);
  // 标题样式配置
  const [headingStyles, setHeadingStyles] = useState<Record<number, React.CSSProperties>>({
    1: { fontSize: '24px', fontWeight: 700, margin: '20px 0 16px 0' },
    2: { fontSize: '20px', fontWeight: 600, margin: '16px 0 12px 0' },
    3: { fontSize: '16px', fontWeight: 600, margin: '12px 0 8px 0' },
  });

  // 分析内容中的标题层级
  useEffect(() => {
    const analyzeHeadings = () => {
      const headingRegex = /^(#{1,3})\s+(.+)$/gm;
      const headingMatches: { level: number; text: string }[] = [];
      
      let match;
      while ((match = headingRegex.exec(content)) !== null) {
        const level = match[1].length;
        const text = match[2];
        headingMatches.push({ level, text });
      }

      // 统计各级标题数量
      const headingCount = headingMatches.reduce<Record<number, { count: number; texts: string[] }>>((acc, heading) => {
        if (!acc[heading.level]) {
          acc[heading.level] = { count: 0, texts: [] };
        }
        acc[heading.level].count++;
        acc[heading.level].texts.push(heading.text);
        return acc;
      }, {});

      // 格式化标题信息
      const formattedHeadings = Object.entries(headingCount).map(([level, info]) => ({
        level: parseInt(level),
        text: info.texts[0] || `H${level} 标题`,
        count: info.count,
      }));

      setHeadings(formattedHeadings);
    };

    analyzeHeadings();
  }, [content]);

  // 主题切换处理
  const handleThemeChange = (theme: string) => {
    setSelectedTheme(theme);
    
    // 基于主题更新标题样式
    const themeColors = themes[theme as keyof typeof themes];
    const newHeadingStyles = {
      1: {
        ...headingStyles[1],
        color: themeColors.primary,
      },
      2: {
        ...headingStyles[2],
        color: themeColors.primary,
      },
      3: {
        ...headingStyles[3],
        color: themeColors.secondary,
      },
    };
    
    setHeadingStyles(newHeadingStyles);
    onStyleChange({ theme, headingStyles: newHeadingStyles });
  };

  return (
    <div className="style-manager" style={{
      background: 'white',
      border: '1px solid #e1e5e9',
      borderRadius: '12px',
      padding: '20px',
      height: '100%',
      overflowY: 'auto',
    }}>
      <h3 style={{ fontSize: '16px', fontWeight: '600', color: '#333', marginBottom: '20px' }}>
        样式管理
      </h3>

      {/* 标题层级统计 */}
      <div style={{ marginBottom: '24px' }}>
        <h4 style={{ fontSize: '14px', fontWeight: '600', color: '#666', marginBottom: '12px' }}>
          标题层级统计
        </h4>
        <div style={{ fontSize: '13px', color: '#999' }}>
          {headings.length > 0 ? (
            <ul style={{ listStyleType: 'none', padding: 0, margin: 0 }}>
              {headings.map((heading, index) => (
                <li key={index} style={{ marginBottom: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <span style={{ 
                    color: heading.level === 1 ? '#667eea' : heading.level === 2 ? '#764ba2' : '#999',
                    fontWeight: '600'
                  }}>
                    H{heading.level}
                  </span>
                  <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {heading.text}
                  </span>
                  <span style={{ color: '#ccc', fontSize: '12px' }}>
                    ({heading.count})
                  </span>
                </li>
              ))}
            </ul>
          ) : (
            <p>未检测到标题内容</p>
          )}
        </div>
      </div>

      {/* 主题色系选择 */}
      <div>
        <h4 style={{ fontSize: '14px', fontWeight: '600', color: '#666', marginBottom: '12px' }}>
          主题色系选择
        </h4>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px' }}>
          {Object.entries(themes).map(([theme, colors]) => (
            <button
              key={theme}
              onClick={() => handleThemeChange(theme)}
              style={{
                padding: '10px',
                border: `2px solid ${selectedTheme === theme ? colors.accent : '#e1e5e9'}`,
                borderRadius: '8px',
                background: selectedTheme === theme ? `${colors.background}80` : 'white',
                cursor: 'pointer',
                transition: 'all 0.3s ease',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                gap: '6px',
              }}
            >
              <div 
                style={{
                  width: '30px',
                  height: '30px',
                  borderRadius: '50%',
                  background: colors.primary,
                }}
              />
              <span style={{ fontSize: '12px', fontWeight: '500', color: '#666' }}>
                {theme.charAt(0).toUpperCase() + theme.slice(1)}
              </span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

export default StyleManager;